Developing a RESTful API with Go and Gin
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type album struct {
ID string `JSON:"id"`
Title string `JSON:"title"`
Artist string `JSON:"artist"`
Price float32 `JSON:"price"`
}
var albums = []album{
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
func main() {
router := gin.Default()
router.GET("/", getAlbums)
router.GET("/:id", getAlbumById)
router.POST("/", addAlbum)
router.Run("localhost:8080")
}
func getAlbums(c *gin.Context) {
return c.IndentedJSON(http)
}
func addAlbum(c *gin.Context) {
var newAlbum album
if err := c.BindJSON(&newAlbum); err != nil {
return
}
albums = append(albums, newAlbum)
c.IndentedJSON(http.StatusOK, newAlbum)
}
func getAlbumById(c *gin.Context) {
id := c.Param("id")
for _, item := range albums {
if item.ID == id {
c.IndentedJSON(http.StatusOK, item)
return
}
}
c.IndentedJSON(http.StatusOK, gin.H{"message": "album not found"})
}